package com.sansan.qiangji.utils;

import com.sansan.qiangji.config.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class RedisUtil {
    private RedisConfig redisConfig;

    @Autowired
    private void setRedisConfig(RedisConfig redisConfig) {
        this.redisConfig = redisConfig;
    }

    /**
     * 往Hash中存入多个数据
     *
     * @param key Redis键
     * @param values Hash键值对
     */
    public <T> void hPutAll(final String key, final Map<String, T> values) throws IOException {
        Jedis jedis = new Jedis(redisConfig.getHost(), redisConfig.getPort());
        if (!redisConfig.getPassword().equals("")) {
            jedis.auth(redisConfig.getPassword());
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(values);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            jedis.set(key.getBytes(), bytes);
        }catch (Exception e){
            jedis.close();
            throw e;
        }
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @return Hash对象集合
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> hMultiGet(final String key) throws IOException, ClassNotFoundException {
        Jedis jedis = new Jedis(redisConfig.getHost(), redisConfig.getPort());
        if (!redisConfig.getPassword().equals("")) {
            jedis.auth(redisConfig.getPassword());
        }
        try {
            byte[] bytes = jedis.get(key.getBytes());
            ObjectInputStream objectInputStream;
            ByteArrayInputStream byteArrayInputStream;
            byteArrayInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Map<String, T> result = (Map<String, T>) objectInputStream.readObject();
            List<T> objectList = new ArrayList<>();
            Set<Map.Entry<String, T>> entrySet = result.entrySet();
            for (Map.Entry<String, T> e : entrySet) {
                objectList.add(e.getValue());
            }
            return objectList;
        }catch (Exception e){
            jedis.close();
            throw e;
        }
    }


}
